package org.example.linkedList;

import java.util.Arrays;

/**
 * @Auther: wangbw
 * @Date:2020/12/16
 * @Description: org.example.linkedList
 * @version: 1.0
 */
public class QuickSort {
    /*先排序，后拆分*/
    public static void main(String[] args) {
        int[] arr = new int[]{4, 5, 3, 2, 8};
        sort(arr);
        print(arr);
        int[] arr1 = new int[]{4, 5, 3, 2, 8};
        sort(arr1);
        print(arr1);
    }

    private static void sort(int[] arr) {
        if (arr == null || arr.length <= 1)
            return;
        sort(arr, 0, arr.length - 1);
    }

    private static void sort(int[] arr, int start, int end) {
        if (start >= end) return;
        int mid = part(arr, start, end);
        sort(arr, start, mid - 1);
        sort(arr, mid + 1, end);
    }

    private static int part(int[] arr, int start, int end) {
        int i = start;
        int j = start;
        int part = arr[end];
        while (j < end) {
            if (arr[j] < part) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
            }
            j++;
        }
        arr[end] = arr[i];
        arr[i] = part;
        return i;
    }

    private static int part1(int[] arr, int start, int end) {
        int i = start;
        int j = end + 1;
        int part = arr[start];
        while (true) {
            while (i >= end || arr[++i] < part)
                break;
            while (j <= start || arr[--j] > part)
                break;
            if (i >= j) break;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        int temp = arr[j];
        arr[j] = arr[start];
        arr[start] = temp;
        return j;
    }

    private static void print(int[] arr) {
        System.out.println("result:" + Arrays.toString(arr));
    }
}
